package com.minggo.charmword.logic;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.minggo.charmword.R;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

/**
 * 复制数据库
 * @author minggo
 * @date 2014-10-23 上午9:52:45
 */
public class CopyDatabaseUtil extends AsyncTask<Void, Void, Boolean> {

	private Context context;
	private Handler handler;
	
	public static final int COPY_DATABASE = 10005;
	
	public CopyDatabaseUtil(Context context,Handler handler){
		this.context = context;
		this.handler = handler;
	}
	
	@Override
	protected Boolean doInBackground(Void... params) {
		
		copyDatabase();
		
		return true;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		handler.sendEmptyMessage(COPY_DATABASE);
	}
	
	
	/**
	 * 拷贝数据库
	 */
	private void copyDatabase() {
		String DB_PATH = context.getFilesDir().getPath() + "/databases/";
		String DB_NAME = "charmword.db";
		byte[] encryptedKey = "minggo620".getBytes();
		File dfile = new File(DB_PATH, DB_NAME);
		if (!dfile.exists()) {
			createDir(new String[] { "/databases"});
			InputStream inputStream = null;
			FileOutputStream outputStream = null;
			try {
				inputStream = context.getResources().openRawResource(R.raw.charmword);
				if (inputStream != null) {
					outputStream = new FileOutputStream(dfile);
					byte[] buffer = new byte[1024];
					int count = 0;
					int  pos, keylen;
					pos = 0;
					keylen = encryptedKey.length;
					while ((count = inputStream.read(buffer)) > 0) {
						for (int i = 0; i < count; i++) {
							buffer[i] ^= encryptedKey[pos];
							outputStream.write(buffer[i]);
							pos++;
							if (pos == keylen)
								pos = 0;
						}
						//outputStream.write(buffer, 0, count);
					}
					outputStream.flush();
				}

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (outputStream != null) {
						outputStream.close();
						outputStream = null;
					}
					if (inputStream != null) {
						inputStream.close();
						inputStream = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}
	
	/**
	 * 
	 */
	public void createDir(String dirs[]) {
		File dir;
		for (String string : dirs) {
			dir = new File(context.getFilesDir().getPath() + string);
			if (!dir.exists()) {
				dir.mkdir();
			}
		}
	}
}
